<template>
  <div class="invoice-receipt-edit">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>编辑到票记录</span>
        </div>
      </template>

      <el-form ref="formRef" :model="formData" label-width="120px" size="small" class="edit-form" label-position="left">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="发票编号" prop="invoiceNo">
              <el-input v-model="formData.invoiceNo" placeholder="发票编号" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收款日期" prop="receiptDate">
              <el-date-picker v-model="formData.receiptDate" type="datetime" placeholder="选择收款日期" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="收款金额" prop="receiptAmount">
              <el-input v-model.number="formData.receiptAmount" placeholder="收款金额" type="number" :min="0" step="0.01" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收款状态" prop="receiptStatus">
              <el-select v-model.number="formData.receiptStatus" placeholder="请选择收款状态" style="width: 100%">
                <el-option label="未收款" value="0" />
                <el-option label="部分收款" value="1" />
                <el-option label="已收款" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="付款方式" prop="paymentMethod">
              <el-input v-model="formData.paymentMethod" placeholder="付款方式" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交易单号" prop="transactionNo">
              <el-input v-model="formData.transactionNo" placeholder="交易单号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="24">
            <el-form-item label="备注" prop="remarks">
              <el-input v-model="formData.remarks" placeholder="备注" type="textarea" :rows="4" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" style="text-align: center">
            <el-button type="primary" @click="handleSubmit">保存</el-button>
            <el-button @click="handleCancel">取消</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { APIs } from '@/Http/http'
import { useCounterStore } from '@/stores/counter'

// 定义到票详情类型
interface InvoiceReceiptDetail {
  receiptId: number
  invoiceId: number
  invoiceNo: string
  receiptDate: string
  receiptAmount: number
  receiptStatus: number
  receiptStatusName: string
  paymentMethod: string
  transactionNo: string
  remarks: string
  createName: string
  createTime: string
  updateName: string
  updateTime: string
}

// 初始化组件
const router = useRouter()
const route = useRoute()
const store = useCounterStore()
const formRef = ref()
const loading = ref(false)

// 获取路由参数receiptId
const receiptId = Number(route.params.receiptId) || 0

// 初始化表单数据
const formData = reactive<InvoiceReceiptDetail>({
  receiptId: 0,
  invoiceId: 0,
  invoiceNo: '',
  receiptDate: '',
  receiptAmount: 0,
  receiptStatus: 0,
  receiptStatusName: '',
  paymentMethod: '',
  transactionNo: '',
  remarks: '',
  createName: '',
  createTime: '',
  updateName: '',
  updateTime: ''
})

/**
 * 获取到票详情
 */
const getInvoiceReceiptDetail = () => {
  loading.value = true

  // 构建请求参数
  const params = {
    receiptId: receiptId
  }

  // 调用API获取详情数据
  APIs.get('/api/SalesInvoice/GetInvoiceReceiptDetail', { params }).then((res: any) => {
    // 处理响应数据
    if (res && res.status === 200 && res.data && res.data.code === 100) {
      const detailData = res.data.data || {}
      // 将获取到的详情数据填充到表单
      formData.receiptId = detailData.receiptId || 0
      formData.invoiceId = detailData.invoiceId || 0
      formData.invoiceNo = detailData.invoiceNo || ''
      // 格式化日期时间
      if (detailData.receiptDate) {
        formData.receiptDate = new Date(detailData.receiptDate).toISOString().substring(0, 16)
      }
      formData.receiptAmount = detailData.receiptAmount || 0
      formData.receiptStatus = detailData.receiptStatus || 0
      formData.receiptStatusName = detailData.receiptStatusName || ''
      formData.paymentMethod = detailData.paymentMethod || ''
      formData.transactionNo = detailData.transactionNo || ''
      formData.remarks = detailData.remarks || ''
      formData.createName = detailData.createName || ''
      formData.createTime = detailData.createTime || ''
      formData.updateName = detailData.updateName || ''
      formData.updateTime = detailData.updateTime || ''
    } else {
      ElMessage.error(res?.data?.msg || '获取到票详情失败')
    }
  }).catch((error: any) => {
    ElMessage.error(error?.response?.data?.message || '请求失败')
  }).finally(() => {
    loading.value = false
  })
}

/**
 * 提交表单数据
 */
const handleSubmit = () => {
  // 表单验证
  if (!formRef.value) return

  formRef.value.validate((valid: boolean) => {
    if (valid) {
      loading.value = true

      // 构建提交参数
      const submitData = {
        receiptId: formData.receiptId,
        receiptDate: formData.receiptDate ? new Date(formData.receiptDate).toISOString() : '',
        receiptAmount: formData.receiptAmount,
        receiptStatus: formData.receiptStatus,
        paymentMethod: formData.paymentMethod,
        transactionNo: formData.transactionNo,
        remarks: formData.remarks,
        updateName: store.Users.userNickname || ''
      }

      // 调用API提交更新数据
      APIs.put('/api/SalesInvoice/UpdateInvoiceReceipt', submitData).then((res: any) => {
        // 处理响应数据
        if (res && res.status === 200 && res.data && res.data.code === 100) {
          ElMessage.success('保存成功')
          // 保存成功后返回列表页面
          router.push('/InvoiceList')
        } else {
          ElMessage.error(res?.data?.msg || '保存失败')
        }
      }).catch((error: any) => {
        ElMessage.error(error?.response?.data?.message || '请求失败')
      }).finally(() => {
        loading.value = false
      })
    }
  })
}

/**
 * 取消操作，返回列表页面
 */
const handleCancel = () => {
  ElMessageBox.confirm(
    '确定要取消编辑吗？未保存的更改将丢失。',
    '取消确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(() => {
    router.push('/InvoiceList')
  }).catch(() => {
    // 用户取消操作，不做处理
  })
}

// 组件挂载时加载详情数据
onMounted(() => {
  getInvoiceReceiptDetail()
})
</script>

<style scoped>
.invoice-receipt-edit {
  padding: 12px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.edit-form {
  margin-bottom: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
}

/* 确保表单项对齐的样式 */
.edit-form .el-form-item {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}

/* 确保输入组件的宽度一致 */
.edit-form .el-input,
.edit-form .el-select,
.edit-form .el-date-picker {
  width: 100%;
}
</style>